package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private static ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    WmsFeignService wmsFeignService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        // 获取主线程的ThreadLocal 的数据
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        System.out.println("主线程...." + Thread.currentThread().getId());
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            // 共享主线程的数据，因为setRequestAttributes设置的是ThreadLocal 类型的
            RequestContextHolder.setRequestAttributes(requestAttributes);
            System.out.println("member...." + Thread.currentThread().getId());

            //1、远程查询所有的收货地址列表
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            orderConfirmVo.setAddressList(address);
        }, threadPoolExecutor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            System.out.println("cart...." + Thread.currentThread().getId());

            //2、远程查询购物车所有选中的购物项
            List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
            orderConfirmVo.setItems(currentUserCartItems);
        }, threadPoolExecutor).thenRunAsync(() -> {
            // 查询商品有货没货
            List<Long> collect = orderConfirmVo.getItems().stream()
                    .map(OrderItemVo::getSkuId)
                    .collect(Collectors.toList());
            R r = wmsFeignService.getSkusHasStock(collect);
            if (r.getCode() == 0) {
                List<SkuStockVo> data = r.getData(new TypeReference<List<SkuStockVo>>() {
                });
                if (data != null) {
                    Map<Long, Boolean> collect1 = data.stream()
                            .collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                    orderConfirmVo.setStocks(collect1);
                }
            }
        }, threadPoolExecutor);


        // feign在远程调用的时候会新构造一个什么都没有的请求体，请求体找构造的时候
        // RequestInterceptor interceptor : requestInterceptors 对请求体增加东西

        //3、查询用户积分
        orderConfirmVo.setIntegration(memberRespVo.getIntegration());

        //4、其他数据自动计算
        //5、TODO 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token);
        orderConfirmVo.setOrderToken(token);

        CompletableFuture.allOf(getAddressFuture, cartFuture).get();
        return orderConfirmVo;
    }

    // 同一个对象内事务方法互调失效。原因：绕过了动态代理对象
    // 事务使用代理对象来控制的
    @Transactional(timeout = 30) // a 事务的所有设置会传播到和他公用一个事务的方法
    public void a() {
        // b,c做任何设置都没用。都是和a同一个事务
        // this.b(); 没用
        // this.c(); 没用
        OrderServiceImpl orderService = (OrderServiceImpl) AopContext.currentProxy();
        orderService.b();
        orderService.c();
//        bService.b(); // a 事务
//        cService.c(); // 新事物（不回滚）
        int i = 1 / 0;
    }

    @Transactional(propagation = Propagation.REQUIRED, timeout = 2) // 设置的timeout不管用，因为你使用的事务是a的
    public void b() {

    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, timeout = 20) // 管用
    public void c() {

    }

    // 本地事务，在分布式系统，只能控制自己的回滚，控制不了其他服务的回滚
    // 分布式事务：最大原因，网络问题 + 分布式（不同数据库）
    // REPEATABLE_READ,REQUIRED,REQUIRES_NEW
//    @GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderRespVo submitOrder(OrderSubmitVo vo) {
        orderSubmitVoThreadLocal.set(vo);
        SubmitOrderRespVo response = new SubmitOrderRespVo();
        response.setCode(0);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        // 1. 验证令牌【令牌的对比和删除必须保证原子性】
        // 0 令牌验证失败 1 删除成功
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        // 原子性验证令牌和删除令牌
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if (result.equals(0L)) {
            // 令牌验证失败
            response.setCode(1);
            return response;
        } else {
            // 令牌验证成功
            //下单：去创建订单，验令牌，验价格，锁库存...
            // 创建订单、订单项等信息
            OrderCreateTo order = createOrder();
            // 验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            // 误差小于0.01 都算正常
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                // TODO 保存订单
                saveOrder(order);
                // 锁定库存。只要有异常就回滚订单数据。
                // 订单号，所有订单项（skuId，skuName，num)
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> collect = order.getOrderItems().stream()
                        .map(item -> {
                            OrderItemVo orderItemVo = new OrderItemVo();
                            orderItemVo.setSkuId(item.getSkuId());
                            orderItemVo.setCount(item.getSkuQuantity());
                            orderItemVo.setTitle(item.getSkuName());
                            return orderItemVo;
                        }).collect(Collectors.toList());
                lockVo.setLocks(collect);
                // TODO 远程锁库存
                // 库存成功了，但是网络原因超时了，订单回滚，库存不回滚
                // 为了保证高并发。库存服务自己回滚。可以发消息给库存服务；
                // 库存服务本身也可以使用自动解锁模式 消息队列
                R r = wmsFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0) {
                    // 锁成功
                    response.setOrder(order.getOrder());

                    // TODO 远程扣减积分
//                    int i = 1 / 0; // 订单回滚，库存不回滚
                    // TODO 订单创建成功发送消息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return response;
                } else {
                    // 锁定失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }

            } else {
                response.setCode(2);
                return response;
            }
        }

    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity orderEntity = baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    /**
     * 关闭订单
     *
     * @param entity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        // 查询当前这个订单的最新转态
        OrderEntity byId = this.getById(entity.getId());
        if (byId.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            // 关单
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setId(byId.getId());
            orderEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            baseMapper.updateById(orderEntity);

            // 发给MQ 我已经解锁订单了。
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(byId, orderTo);
            try {
                // TODO 保证消息一定会发送出去，每一个消息都可以做好日记记录（给数据库保存每一个消息的详细信息）
                // TODO 定期扫描数据库将失败的消息在发送一遍
                rabbitTemplate.convertAndSend("order-event-exchange", "stock.release.other", orderTo);

            } catch (Exception e) {
                // TODO 重新发送（意义不大，万一是服务器宕机了）
//                while
            }
        }
    }

    /**
     * 获取当前订单的支付信息
     *
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        PayVo payVo = new PayVo();
        payVo.setTotal_amount(order.getTotalAmount().setScale(2, BigDecimal.ROUND_UP).toString()); // 订单的金额
        List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        payVo.setSubject(list.get(0).getSkuName()); // 订单的主题

        payVo.setBody(list.get(0).getSkuAttrsVals()); // 订单的备注
        payVo.setOut_trade_no(order.getOrderSn()); // 订单号
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );
        // 封装订单项数据
        List<OrderEntity> order_sn1 = page.getRecords().stream().map(item -> {
            List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", item.getOrderSn()));
            item.setItemEntities(order_sn);
            return item;
        }).collect(Collectors.toList());
        page.setRecords(order_sn1);
        return new PageUtils(page);
    }

    /**
     * 处理支付宝的处理结果
     *
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        // 1.保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(vo.getTrade_no());
        paymentInfoEntity.setOrderSn(vo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(vo.getTrade_status());
        paymentInfoEntity.setCreateTime(new Date());
        paymentInfoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(paymentInfoEntity);

        // 2.修改订单的转态信息
        if (vo.getTrade_status().equals("TRADE_FINISHED") || vo.getTrade_status().equals("TRADE_SUCCESS")) {
            // 支付成功
            String out_trade_no = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(out_trade_no, OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo to) {
        // TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(to.getOrderSn());
        orderEntity.setMemberId(to.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = to.getSeckillPrice().multiply(new BigDecimal("" + to.getNum()));
        orderEntity.setPayAmount(multiply);
        orderEntity.setTotalAmount(multiply);
        this.save(orderEntity);

        // TODO 保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(to.getOrderSn());
        itemEntity.setRealAmount(multiply);
        itemEntity.setSkuQuantity(to.getNum());
        // TODO 获取当前sku 的详细信息进行设置，productFeignService.getSpuInfoBySkuId()
        orderItemService.save(itemEntity);
    }

    /**
     * 保存订单数据
     *
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        // 使用seata控制分布式事务 不能使用批处理，只能一个个操作
        List<OrderItemEntity> orderItems = order.getOrderItems();
        for (OrderItemEntity orderItem : orderItems) {
            orderItemService.save(orderItem);
        }
        // exception Error updating database. Cause: io.seata.common.exception.NotSupportYetException
        // io.seata.common.exception.NotSupportYetException: null
//        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        // 1、生成订单号
        String orderSn = IdWorker.getTimeId();// mybatis 提供的工具类
        OrderEntity orderEntity = buildOrder(orderSn);

        // 2、获取所有的订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);

        // 3、计算价格、积分等信息
        computePrice(orderEntity, orderItemEntities);


        createTo.setOrder(orderEntity);
        createTo.setOrderItems(orderItemEntities);
        return createTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        // 订单的总额，叠加每一个订单项的总额信息
        for (OrderItemEntity entity : itemEntities) {
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift = gift.add(new BigDecimal(entity.getGiftGrowth().toString()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }
        // 订单价相关
        orderEntity.setTotalAmount(total);
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegration(integration.intValue());
        orderEntity.setPromotionAmount(promotion);
        // 设置积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0); // 未删除
    }

    /**
     * 构建所有订单项
     *
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        // 最后一次确定每个购物项的价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            List<OrderItemEntity> collect = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 构建指定订单项
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1、订单信息：订单号
        Long skuId = cartItem.getSkuId();
        //2、商品的SPU信息
        R r = productFeignService.getSpuInfoBySkuId(cartItem.getSkuId());
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName((data.getSpuName()));
        itemEntity.setCategoryId(data.getCatalogId());

        //3、商品的SKU信息
        itemEntity.setSkuId(skuId);
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());


        //4、优惠信息【不做】
        //5、积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0.0"));
        itemEntity.setCouponAmount(new BigDecimal("0.0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0.0"));

        // 当前订单项的实际金额 总额 - 各种优惠
        BigDecimal subtract = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()))
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);

        return itemEntity;
    }

    /**
     * 构建订单
     *
     * @param orderSn
     */
    private OrderEntity buildOrder(String orderSn) {

        //创建订单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        orderEntity.setMemberId(memberRespVo.getId());
        OrderSubmitVo submitVo = orderSubmitVoThreadLocal.get();
        //获取收货地址信息
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        FareVo data = fare.getData(new TypeReference<FareVo>() {
        });

        // 设置运费信息
        orderEntity.setFreightAmount(data.getFare());

        //设置收货人信息
        orderEntity.setReceiverCity(data.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(data.getAddress().getDetailAddress());
        orderEntity.setReceiverName(data.getAddress().getName());
        orderEntity.setReceiverPostCode(data.getAddress().getPostCode());
        orderEntity.setReceiverProvince(data.getAddress().getProvince());
        orderEntity.setReceiverRegion(data.getAddress().getRegion());
        // 设置订单的相关状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        return orderEntity;
    }

}